package com.founder.barcode.bussiness.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.founder.barcode.bussiness.code.BuildXml;
import com.founder.barcode.common.util.HttpClientUtil;
import com.founder.barcode.common.util.MsgGenUtil;

public abstract class BaseRequestService extends BaseService {
    
    protected String uri = null;
    
    protected BuildXml buildXml = new BuildXml();
    
    protected String sendRequest(String xmlStr) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("requestXML==" + xmlStr);
        String responseXml = HttpClientUtil.postRequest(uri, xmlStr);
        System.out.println("responseXML==" + responseXml);
        return responseXml;
    }
    
    protected abstract void init();
    
    public BaseRequestService() {
        this.init();
    }
    
    public String encodeByMD5(String originString) {
        if (originString != null) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");

                byte[] results = md.digest(originString.getBytes("UTF-8"));

                String resultString = MsgGenUtil.buf2hex(results);
                return resultString;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
    
    protected String getXml(String uri) throws IOException {
        URL url = this.getClass().getResource(uri);
        String xml = FileUtils.readFileToString(new File(url.getPath()));
        return xml;
    }
    
    protected String replaceXml(String xml,Map<String,String> params) {
        for(Entry<String,String> entry : params.entrySet()) {
            xml = StringUtils.replace(xml, "${" + entry.getKey() + "}", entry.getValue());
        }
        return xml;
    }
    
    public String genTransactionId(String prefix,String suffix) {
        prefix = StringUtils.trimToEmpty(prefix);
        suffix = StringUtils.trimToEmpty(suffix);
        StringBuffer sb = new StringBuffer();
        sb.append(prefix).append(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
        sb.append(new Random().nextInt(9999));
        sb.append(suffix);
        return sb.toString();
    }
    
    public String genTransactionId() {
        return this.genTransactionId(null, null);
    }
}
